<?php
namespace common\components\services\integral;
use common\components\helpers\Fun;
use yii\base\Component;
use common\models\datas\IntegralConfigItem;
use yii\base\ErrorException;
use frontend\models\datas\IntegralRecord;
use common\models\datas\CustomerAccount;

class IntegralEventManage  extends Component{


    public $evenArray;

    public $ownerArray;

    public $eventKey;

    private $_time_filed=['create_at','created_at','updated_at','update_at'];


    public function afterInsertSend(){
//        $config=$this->getConfig();
//        if($this->eventKey>0&&$config!==null){
//            $integralTotal=$this->getIntegralTotal($config);
//            $integralTemplate=$this->getIntegralTemplate($config);
//            $this->writeRecord($integralTotal,$integralTemplate);
//            $this->writeAccount($integralTotal);
//        }
    }

    private function getConfig(){
        return IntegralConfigItem::find()->where(['site_id'=>Fun::getSiteId()])->joinWith(['integralConfig' => function ($query) {
            $query->andWhere(['event_id' => $this->eventKey]);
        },])->one();
    }

    private function getIntegralTotal($config){
        $formula=$config->formula;
        if(is_numeric($formula))return $formula;
        foreach($this->ownerArray as $k=>$v){
            $formula=str_replace('{$'.$k.'}',$v,$formula);
        }
        if(preg_match('/[\+\-\*\/\.]{2}|[^\+\-\*\/\(\)\d\.]+/i',$formula)){
            throw new ErrorException('非法字符');
        }
        $total=eval("return $formula;");
        return $total;
    }

    private function getIntegralTemplate($config){
        $str=$config->template;
        foreach($this->ownerArray as $k=>$v){
            $vl=in_array($k,$this->_time_filed)?\Yii::$app->formatter->asDatetime($v):$v;
            $str=str_replace('{$'.$k.'}',$vl,$str);
        }
        return $str;
    }

    private function writeRecord($total,$template){
        $integral_record=new IntegralRecord();
        $integral_record->integral=$total;
        $integral_record->content=$template;
        $integral_record->site_id=Fun::getSiteId();
        $integral_record->user_id=1;
        $integral_record->customer_id=$this->ownerArray['customer_id'];
        $integral_record->save(false);

    }

    private function writeAccount($total){
        $integral_account=CustomerAccount::findOne(['customer_id'=>$this->ownerArray['customer_id']])!==null?CustomerAccount::findOne(['customer_id'=>$this->ownerArray['customer_id']]):new CustomerAccount();
        $integral_account->customer_id=$this->ownerArray['customer_id'];
        $integral_account->intergral=$total;
        $integral_account->intergral_increase+=$total;
        $integral_account->save(false);
    }

}